package com.pccc.batch.config.remotepartition.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;

public class HttpClientResponse implements ClientHttpResponse {

	
	private static final Logger log = LoggerFactory.getLogger(HttpClientResponse.class);
	
	private HttpResponse response;
	
	private HttpEntity entity;
	
	private HttpHeaders headers;
	
	public HttpClientResponse(HttpResponse response,HttpEntity entity) {
		this.response = response;
		this.entity = entity;
	}
	
	
	@Override
	public InputStream getBody() throws IOException {
		return entity.getContent();
	}

	@Override
	public HttpHeaders getHeaders() {
		HttpHeaders headers = this.headers;
		if (headers == null) {
			headers = new HttpHeaders();
			for (Header header : response.getAllHeaders()) {
				headers.add(header.getName(), header.getValue());
			}
			this.headers = headers;
		}
		return headers;
	}

	@Override
	public HttpStatus getStatusCode() throws IOException {
		return HttpStatus.valueOf(response.getStatusLine().getStatusCode());
	}

	@Override
	public int getRawStatusCode() throws IOException {
		return response.getStatusLine().getStatusCode();
	}

	@Override
	public String getStatusText() throws IOException {
		return response.getStatusLine().getReasonPhrase();
	}

	@Override
	public void close() {
		try {
			EntityUtils.consume(entity);
		} catch (IOException e) {
			log.error(e.getMessage(),e);
		}
	}

}
